<template>
    <div class="x-upload">
        <div v-if="!$attrs.multiple" class="d-flex justify-content-between">
            <el-input v-if="!$attrs.image" clearable :style="$attrs.style" :class="$attrs.class" @clear="clear"
                v-model="inputValue">
                <template #append>
                    <el-upload ref="upload" :multiple="false" :action="uploadPath" :limit="1" :on-exceed="handleExceed"
                        :on-success="onUploadSuccess">
                        <el-button type="primary">{{ $attrs.btnText }}</el-button>
                    </el-upload>
                </template>
            </el-input>

            <el-upload ref="upload" v-else class="ps-2" :on-exceed="handleExceed" :show-file-list="false"
                :action="uploadPath" :on-success="onUploadSuccess">
                <img style="width:120px" v-if="inputValue" :src="inputValue" />
                <el-icon v-else>
                    <Plus />
                </el-icon>
            </el-upload>
            <i class="delIcon iconfont te-i-close  ms-3" @click="deleteImg" v-if="inputValue"></i>
        </div>
        <div v-else>
            <el-upload v-if="!$attrs.image" v-model:file-list="fileList" :action="uploadPath" multiple
                :on-remove="handleRemove" :limit="$attrs.limit" :on-success="onUploadSuccess">
                <el-button type="primary">{{ $attrs.btnText }}</el-button>
                <template #tip>
                    <div class="el-upload__tip" v-if="$attrs.tips">
                        {{ $attrs.tips }}
                    </div>
                </template>
            </el-upload>

            <el-upload v-else v-model:file-list="fileList" :action="uploadPath" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="onUploadSuccess">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
        </div>
        <el-dialog v-model="dialogVisible" append-to-body>
            <img :src="dialogImageUrl" class="w-100" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref, useAttrs } from 'vue';
import type { UploadFile, UploadFiles, UploadProps, UploadInstance, UploadUserFile, UploadRawFile } from 'element-plus'
import { genFileId } from 'element-plus'
import _ from 'lodash';
interface Props {
    modelValue: string[];
}
const attrs = useAttrs();
const props = defineProps<Props>();

const emit = defineEmits(['update:modelValue', 'change']);

const inputValue = ref<string>("")
inputValue.value = props.modelValue as string || "";

const fileList = ref<UploadUserFile[]>([])
if (_.isArray(props.modelValue)) {
    props.modelValue.forEach((file: string) => {
        fileList.value.push({
            name: file,
            url: file,
        })
    })
    inputValue.value = _.head(props.modelValue) || "";
}


// 假设您已经在某个地方定义了 $theia 的类型
// 否则，您可能需要创建一个类型声明文件来定义它
const uploadPath: string = (window as any).$theia.env.join("/file/upload");

//@ts-ignore
const onUploadSuccess = (response: { path: string }, uploadFile: UploadFile, uploadFiles: UploadFiles) => {

    let files: string[] = []
    if (attrs.multiple) {
        uploadFiles.forEach((file: UploadFile) => {
            if (!file.response && file.url) {
                files.push(file.url)
                return
            }
            if (file.response && (file.response as any).path) {
                files.push((window as any).$theia.env.join((file.response as any).path))
            }
        });
    } else {
        if (response.path) {
            files.push((window as any).$theia.env.join((response as any).path))
        }
    }


    emit('update:modelValue', files);
    emit('change', files);
    inputValue.value = _.head(files) || "";
};
const deleteImg = () => {
    emit('update:modelValue', []);
    emit('change', []);
    inputValue.value = "";
}
const upload = ref<UploadInstance>()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let files: string[] = []

    uploadFiles.forEach((file: UploadFile) => {
        if (!file.response && file.url) {
            files.push(file.url)
            return
        }
        if (file.response && (file.response as any).path) {
            files.push((window as any).$theia.env.join((file.response as any).path))
        }
    });
    if (!attrs.multiple) {
        files = files.length > 0 ? [files[0]] : []
    }
    emit('update:modelValue', files);
    emit('change', files);
    inputValue.value = _.head(files) || "";
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const clear = () => {
    emit('update:modelValue', '');
    emit('change', '');
    inputValue.value = '';
};
</script>
<style scoped>
:deep(.el-upload-list--picture-card li) {
    width: 60px;
    height: 60px;
}

:deep(.el-upload-list--picture-card .el-upload--picture-card) {
    width: 60px;
    height: 60px;
}

.delIcon:hover {
    font-weight: bolder;
    cursor: pointer;
}
</style>